package by.grsu.perovskij.page;


import java.util.List;

import org.apache.wicket.markup.html.basic.Label;
import org.apache.wicket.markup.html.link.Link;
import org.apache.wicket.markup.html.list.ListItem;
import org.apache.wicket.markup.html.list.ListView;
import org.apache.wicket.model.Model;
import org.apache.wicket.spring.injection.annot.SpringBean;

import by.grsu.perovskij.dao.PassengerDao;
import by.grsu.perovskij.entity.Passenger;

/**
 * @author Dmitry_Zhivushko
 *
 */
@SuppressWarnings("serial")
public class ListPassengersPage extends BasePage {

	@SpringBean
	private PassengerDao passengerDao;

	public ListPassengersPage() {
		super();

		final List<Passenger> passengers = passengerDao.findAll();

		add(new ListView<Passenger>("list", passengers) {
			
			@Override
			protected void populateItem(final ListItem<Passenger> item) {
				final Passenger passenger = item.getModelObject();
				// add "labels" to display each property of the item
				item.add(new Label("firstName", passenger.getFirstName()));
				item.add(new Label("secondName", passenger.getSecondName()));

				// add link which will forward to the "edit" page
				item.add(new Link<Passenger>("editlink", new Model<Passenger>(passenger)) {
					@Override
					public void onClick() {
						setResponsePage(new EditPassengerPage(passenger));
					}
				});

				// add "link" which removes item from database and reload the
				// page
				item.add(new Link<Passenger>("deletelink", new Model<Passenger>(passenger)) {
					@Override
					public void onClick() {
						passengerDao.delete(getModelObject().getId());
						setResponsePage(ListPassengersPage.class);
					}
				});
			}
		});

		// redirect to the "edit" page using "empty" model to create new item as
		// result
		add(new Link<Passenger>("createLink", new Model<Passenger>(new Passenger())) {
			@Override
			public void onClick() {
				setResponsePage(new EditPassengerPage(getModelObject()));
			}
		});

	}
}